package cn.njyd.corejava.thread.myday04;

import java.util.Arrays;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ThreadLocalRandom;
import java.util.stream.Collectors;

class NetMall{
    private String mallName;

    public String getMallName() {
        return mallName;
    }

    public void setMallName(String mallName) {
        this.mallName = mallName;
    }

    public NetMall(String mallName) {
        this.mallName = mallName;
    }

    public double getPrice(String productName)  {
        try {
            Thread.sleep(1000);
        }catch (Exception e){};
        return ThreadLocalRandom.current().nextDouble()*2+productName.charAt(0);

    }
}

public class CompletableFutureDemo02 {
    public static List<String> getPrice(List<NetMall> list,String productName){
        return list.
                stream().
                map(mall-> {
                    return String.format("《" + productName + "》" + "in %s price is %.2f",
                            mall.getMallName(),
                            mall.getPrice(productName));
                }).
                collect(Collectors.toList());
    }

    public static List<String> getPriceByCompletableFuture(List<NetMall> list,String productName) {
        return list
                .stream()
                .map(netMall -> CompletableFuture.supplyAsync(()->String.format("《"+productName+"》in %s price is %.2f",netMall.getMallName(),netMall.getPrice(productName))))
                .collect(Collectors.toList()).stream().map(c->c.join()).collect(Collectors.toList());
    }
    public static void main(String[] args) {

        List<NetMall> list = Arrays.asList(new NetMall("JD"),
                new NetMall("TB"),new NetMall("PDD"),
                new NetMall("DD"));
        long start = System.currentTimeMillis();
        List<String> result = getPrice(list,"编程思想");
        result.forEach(v-> System.out.println(v));
        long end = System.currentTimeMillis();
        System.out.println("用时"+(end-start));
        start = System.currentTimeMillis();
        getPriceByCompletableFuture(list,"java").forEach(System.out::println);
        end = System.currentTimeMillis();
        System.out.println("第二次"+(end-start));
    }
}
